<template>
  <div class="app-container head">
    <van-nav-bar title="修改头像"  left-arrow @click-left="$router.back()" />
    <br />
    <input type="file" accept="image/*" ref="refFile" style="display: none" v-on:change="fileLoad" />
    <div class="head-img">
      <quick-cropper  ref="cropper" :img-src="imgSrc" @finish="finish"></quick-cropper>
    </div>
    <div style="margin: 54px 16px;">
        <van-button  block class="button-default" type="primary" @click="choose">选择图像</van-button>
        <br />
        <van-button  block type="primary" @click="submit">提交</van-button>
      </div>
  </div>
</template>

<script>

import QuickCropper from '@/components/quick-cropper/index.vue'
import { showLoadingToast, showToast, closeToast } from 'vant'
import { saveHeadImg } from '@/api/user'
import { uploadImg } from '@/api/home'
import { mapActions } from 'pinia'
import { useUserStore } from '@/store/user'

export default {
  name: 'HeadImage',
  components: {
    QuickCropper
  },
  data() {
    return {
      imgSrc: ''
    }
  },
  created() {
    this.choose()
  },
  methods: {
    ...mapActions(useUserStore, ['setAvatar']),
    choose() {
      this.$nextTick(() => {
        this.$refs.refFile.dispatchEvent(new MouseEvent('click'))
      })
    },
    finish(base64, data) {
      uploadImg(data).then(resp => {
        const img = resp.data
        saveHeadImg(img).then(() => {
          closeToast()
          this.setAvatar(img)
          this.$router.back()
        }).catch(err => {
          showToast(err)
        })
      }).catch(err => {
        showToast(err)
      })
    },
    fileLoad() {
      const selectedFile = this.$refs.refFile.files[0]
      let reader = new FileReader()
      reader.readAsDataURL(selectedFile)
      let that = this
      reader.onload = (res) => {
        const result = res.target.result
        that.imgSrc = result
        that.$nextTick(() => {
          that.$refs['cropper'].imgDirection()
        })
      }
    },
    submit() {
      showLoadingToast({ message: '加載中...'})
      this.$refs['cropper'].confirm()
    }
  }
}
</script>
<style>
.head-img {
  margin: auto;
  width: 320px;
  height: 320px;
}
</style>